package com.phpxiu.app.presenters;


import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Handler;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.phpxiu.app.config.Constants;
import com.phpxiu.app.controller.avcontroller.QavsdkControl;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.CurLiveInfo;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.event.OnBackCamera;
import com.phpxiu.app.model.msg.EnterMsg;
import com.phpxiu.app.model.msg.MultiVideoMsg;
import com.phpxiu.app.model.response.MsgModel;
import com.phpxiu.app.presenters.viewinterface.RoomView;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.RoomVideoRoom;
import com.tencent.TIMCallBack;
import com.tencent.TIMConversation;
import com.tencent.TIMConversationType;
import com.tencent.TIMCustomElem;
import com.tencent.TIMElem;
import com.tencent.TIMElemType;
import com.tencent.TIMGroupSystemElem;
import com.tencent.TIMGroupSystemElemType;
import com.tencent.TIMManager;
import com.tencent.TIMMessage;
import com.tencent.TIMMessageListener;
import com.tencent.TIMTextElem;
import com.tencent.TIMUserProfile;
import com.tencent.TIMValueCallBack;
import com.tencent.av.TIMAvManager;
import com.tencent.av.sdk.AVAudioCtrl;
import com.tencent.av.sdk.AVCallback;
import com.tencent.av.sdk.AVEndpoint;
import com.tencent.av.sdk.AVError;
import com.tencent.av.sdk.AVRoomMulti;
import com.tencent.av.sdk.AVVideoCtrl;
import com.tencent.av.sdk.AVView;
import com.tencent.bugly.imsdk.crashreport.CrashReport;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;


import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * @file
 * @brief 直播间业务逻辑处理类
 * @author 吴金洲
 * @note  直播间业务逻辑处理类
 *
 */
@Deprecated
public class RoomPresenter extends BasePresenter {
    private RoomView mRoomView;
    public Context mContext;
    private static final String TAG = RoomPresenter.class.getSimpleName();
    private static final int FRONT_CAMERA = 0;
    private static final int BACK_CAMERA = 1;
    private static final int MAX_REQUEST_VIEW_COUNT = 4; //当前最大支持请求画面个数
    private static final boolean REMOTE = false;
    public TIMConversation mGroupConversation;
    public TIMConversation mC2CConversation;
    private boolean isMicOpen = true;
    private AVView mRequestViewList[] = new AVView[MAX_REQUEST_VIEW_COUNT];
    private String mRequestIdentifierList[] = new String[MAX_REQUEST_VIEW_COUNT];
    private Boolean isOpenCamera = false;
    private static Gson gson=new Gson();
    private final static int CAMERA_EFFECT_VALUE=80;//0~100,取固定值50 美颜效果
    private final static int CAMERA_EFFECT_WHITE=30;//0~100,取固定值30 美白效果
    private boolean mIsFrontCamera = true;//前置摄像头
    /**
     * 开关闪光灯
     */
    private boolean flashLgihtStatus = false;//闪光灯状态是否为开

    public RoomPresenter(Context context, RoomView interfaceView) {
        mContext = context;
        mRoomView = interfaceView;

    }

    private AVVideoCtrl.CameraPreviewChangeCallback mCameraPreviewChangeCallback = new AVVideoCtrl.CameraPreviewChangeCallback() {
        @Override
        public void onCameraPreviewChangeCallback(int cameraId) {
            //设置镜像显示方式
            QavsdkControl.getInstance().setMirror(FRONT_CAMERA == cameraId);
            QavsdkControl.getInstance().getAVContext().getVideoCtrl().inputBeautyParam(getBeautyProgress(CAMERA_EFFECT_VALUE));//美颜度
            QavsdkControl.getInstance().getAVContext().getVideoCtrl().inputWhiteningParam(getBeautyProgress(CAMERA_EFFECT_WHITE));//美白度
        }
    };

    private float getBeautyProgress(int progress) {
        return (9.0f * progress / 100.0f);
    }
    /**
     * 摄像头变动回调
     */
    public void setCameraPreviewChangeCallback() {
        AVVideoCtrl avVideoCtrl = QavsdkControl.getInstance().getAVContext().getVideoCtrl();
        avVideoCtrl.setCameraPreviewChangeCallback(mCameraPreviewChangeCallback);
    }

    /**
     * 开启摄像头和MIC
     */
    public void openCameraAndMic() {
        openCamera();
        AVAudioCtrl avAudioCtrl = QavsdkControl.getInstance().getAVContext().getAudioCtrl();//开启Mic
        avAudioCtrl.enableMic(true);
        isMicOpen = true;

    }

    /**
     * 打开摄像头
     */
    private void openCamera() {
        if (mIsFrontCamera) {
            enableCamera(FRONT_CAMERA, true);
        } else {
            enableCamera(BACK_CAMERA, true);
        }
    }

    public void closeCameraAndMic() {
        closeCamera();
        closeMic();
    }

    /**
     * 开关摄像头
     */
    public void toggleCamera() {
        if (isOpenCamera) {
            closeCamera();
        } else {
            openCamera();
        }
    }


    /**
     * 开关Mic
     */
    public void toggleMic() {
        if (isMicOpen) {
            openMic();
        } else {
            muteMic();
        }
    }

    public void closeCamera() {
        if (mIsFrontCamera) {
            enableCamera(FRONT_CAMERA, false);
        } else {
            enableCamera(BACK_CAMERA, false);
        }
    }

    public void closeMic() {
        AVAudioCtrl avAudioCtrl = QavsdkControl.getInstance().getAVContext().getAudioCtrl();//开启Mic
        avAudioCtrl.enableMic(false);
        isMicOpen = false;
    }

    /**
     * 开启摄像头
     *
     * @param camera
     * @param isEnable
     */
    private void enableCamera(final int camera, boolean isEnable) {
        if (isEnable) {
            isOpenCamera = true;
        } else {
            isOpenCamera = false;
        }
        AVVideoCtrl avVideoCtrl = QavsdkControl.getInstance().getAVContext().getVideoCtrl();
        //打开摄像头
        int ret = avVideoCtrl.enableCamera(camera, isEnable, new AVVideoCtrl.EnableCameraCompleteCallback() {
            protected void onComplete(boolean enable, int result) {//开启摄像头回调
                super.onComplete(enable, result);
                if (result == AVError.AV_OK) {//开启成功
                    if (camera == FRONT_CAMERA) {
                        mIsFrontCamera = true;
                    } else {
                        mIsFrontCamera = false;
                    }

                }
            }
        });
    }

    /**
     * AVSDK 请求主播数据
     *
     * @param identifiers 主播ID
     */
    public void requestViewList(ArrayList<String> identifiers) {
        if (identifiers.size() == 0) return;
        AVEndpoint endpoint = ((AVRoomMulti) QavsdkControl.getInstance().getAVContext().getRoom()).getEndpointById(identifiers.get(0));
        if (endpoint != null) {
            ArrayList<String> alreadyIds = QavsdkControl.getInstance().getRemoteVideoIds();//已经存在的IDs
            for (String id : identifiers) {//把新加入的添加到后面
                alreadyIds.add(id);
            }
            int viewIndex = 0;
            for (String id : alreadyIds) {//一并请求
                if (viewIndex >= 4) break;
                AVView view = new AVView();
                view.videoSrcType = AVView.VIDEO_SRC_TYPE_CAMERA;
                view.viewSizeType = AVView.VIEW_SIZE_TYPE_BIG;
                //界面数
                mRequestViewList[viewIndex] = view;
                mRequestIdentifierList[viewIndex] = id;
                viewIndex++;
            }
            QavsdkControl.getInstance().getAvRoomMulti().requestViewList(mRequestIdentifierList, mRequestViewList, alreadyIds.size(), mRequestViewListCompleteCallback);
        }
    }

    private AVRoomMulti.RequestViewListCompleteCallback mRequestViewListCompleteCallback = new AVRoomMulti.RequestViewListCompleteCallback() {
        @Override
        public void OnComplete(String[] identifierList, AVView[] avViews, int i, int i2, String s) {
            for (String id : identifierList) {
                mRoomView.showVideoView(REMOTE, id);
            }
        }
    };


    /**
     * 初始化聊天室  设置监听器
     */
    public void initTIMListener(String chatRoomId) {
        mGroupConversation = TIMManager.getInstance().getConversation(TIMConversationType.Group, chatRoomId);
        TIMManager.getInstance().addMessageListener(msgListener);
        if(MySelfInfo.getInstance().getIdStatus()!= Constants.HOST){
            mC2CConversation = TIMManager.getInstance().getConversation(TIMConversationType.C2C, CurLiveInfo.getHostID());//与主播的会话
        }
    }


    /**
     * 发送纯文本群消息
     * @param Nmsg
     */
    public void sendGroupText(TIMMessage Nmsg) {
        if (mGroupConversation != null)
            mGroupConversation.sendMessage(Nmsg, new TIMValueCallBack<TIMMessage>() {
                @Override
                public void onError(int i, String s) {
                    if (i == 85) { //消息体太长
                        Toast.makeText(mContext,mContext.getString(R.string.room_group_msg_too_long), Toast.LENGTH_SHORT).show();
                    } else if (i == 6011) {//群主不存在
                        if(KKYUtil.DEBUG){
                            Toast.makeText(mContext, "Host don't exit ", Toast.LENGTH_SHORT).show();
                        }
                    }
                }

                @Override
                public void onSuccess(TIMMessage timMessage) {
                    if(true) {
                        if(mRoomView ==null){
                            CrashReport.postCatchedException(new NullPointerException("LiveHelper.java:254行mLiveView==null"));
                        }
                        if(mRoomView !=null){
                            mRoomView.onReceiveMsg(timMessage);
                        }
                        return;
                    }
                    //发送成回显示消息内容
                    for (int j = 0; j < timMessage.getElementCount(); j++) {
                        TIMElem elem = (TIMElem) timMessage.getElement(0);
                        if (timMessage.isSelf()) {
                            handleTextMessage(elem, MySelfInfo.getInstance().getNickName());
                        } else {
                            TIMUserProfile sendUser = timMessage.getSenderProfile();
                            String name;
                            if (sendUser != null) {
                                name = sendUser.getNickName();
                            } else {
                                name = timMessage.getSender();
                            }
                            //String sendId = timMessage.getSender();
                            handleTextMessage(elem, name);
                        }
                    }
                }
            });
    }

    /**
     * 发送纯文本群消息
     * @param textMsg
     */
    public void sendGroupText(TIMMessage textMsg,TIMValueCallBack<TIMMessage> callBack) {
        if (mGroupConversation != null)
            mGroupConversation.sendMessage(textMsg,callBack);
    }

    /**
     * 发送自定义群消息
     * @param cmd
     * @param param
     * @param callback
     */
    public void sendGroupMessage(int cmd, String param, TIMValueCallBack<TIMMessage> callback) {
        JSONObject inviteCmd = new JSONObject();
        try {
            inviteCmd.put(Constants.CMD_KEY, cmd);
            inviteCmd.put(Constants.CMD_PARAM, param);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String cmds = inviteCmd.toString();
        TIMMessage Gmsg = new TIMMessage();
        TIMCustomElem elem = new TIMCustomElem();
        elem.setData(cmds.getBytes());
        elem.setDesc("");
        Gmsg.addElement(elem);
        if (mGroupConversation != null)
            mGroupConversation.sendMessage(Gmsg, callback);
    }

    /**
     * 发送自定义通知的群消息，消息级别为红包级别的,级别最高
     * @param  customMsg 自己定义消息json格式的
     * @param callback
     */
    public void sendGroupNoticeMessage(String customMsg, TIMValueCallBack<TIMMessage> callback) {
        TIMMessage gMsg2 = new TIMMessage();
        TIMCustomElem elem = new TIMCustomElem();
        elem.setData(customMsg.getBytes());
        elem.setDesc("");
        gMsg2.addElement(elem);
        if (mGroupConversation != null) {
            mGroupConversation.sendRedPacketMessage(gMsg2, callback);
        }
    }

    /**
     * 发送自定义通知的群消息，消息级别为点赞级别的,级别最低
     * @param  customMsg 自己定义消息json格式的
     * @param callback
     */
    public void sendGroupNoticeMsg(String customMsg, TIMValueCallBack<TIMMessage> callback) {
        TIMMessage gMsg2 = new TIMMessage();
        TIMCustomElem elem = new TIMCustomElem();
        elem.setData(customMsg.getBytes());
        elem.setDesc("");
        gMsg2.addElement(elem);
        if (mGroupConversation != null) {
            mGroupConversation.sendLikeMessage(gMsg2,callback);
        }
    }

    /**
     * 发送自定义群消息
     * @param cmd
     * @param param
     */
    public void sendGroupMessage(int cmd, String param) {
        sendGroupMessage(cmd, param, new TIMValueCallBack<TIMMessage>() {
            @Override
            public void onError(int i, String s) {
                if (i == 85) { //消息体太长
                } else if (i == 6011) {//群主不存在
                }
            }

            @Override
            public void onSuccess(TIMMessage timMessage) {
            }
        });
    }

    /**
     * 发送点对点在线消息
     * @param cmd
     * @param Param
     * @param sendId
     */
    public void sendC2COnlineMsg(final int cmd, String Param, final String sendId){
        JSONObject inviteCmd = new JSONObject();
        try {
            inviteCmd.put(Constants.CMD_KEY, cmd);
            inviteCmd.put(Constants.CMD_PARAM, Param);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String cmds = inviteCmd.toString();
        TIMMessage msg = new TIMMessage();
        TIMCustomElem elem = new TIMCustomElem();
        elem.setData(cmds.getBytes());
        elem.setDesc("");
        msg.addElement(elem);
        mC2CConversation = TIMManager.getInstance().getConversation(TIMConversationType.C2C, sendId);
        mC2CConversation.sendOnlineMessage(msg, new TIMValueCallBack<TIMMessage>() {
            @Override
            public void onError(int i, String s) {
                KKYUtil.log(TAG, "发送私聊消息错误enter error" + i + ": " + s);
            }

            @Override
            public void onSuccess(TIMMessage timMessage) {
                KKYUtil.log(TAG, "发送私聊消息成功!");
            }
        });
    }

    /**
     * 私聊消息发送
     * @param cmd 协议编号
     * @param Param 消息内容
     * @param receiver 接收消息用户的id
     */
    public void sendC2CMessage(final int cmd, String Param, final String receiver) {
        JSONObject inviteCmd = new JSONObject();
        try {
            inviteCmd.put(Constants.CMD_KEY, cmd);
            inviteCmd.put(Constants.CMD_PARAM, Param);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String cmds = inviteCmd.toString();
        TIMMessage msg = new TIMMessage();
        TIMCustomElem elem = new TIMCustomElem();
        elem.setData(cmds.getBytes());
        elem.setDesc("");
        msg.addElement(elem);
        mC2CConversation = TIMManager.getInstance().getConversation(TIMConversationType.C2C, receiver);
        mC2CConversation.sendMessage(msg, new TIMValueCallBack<TIMMessage>() {
            @Override
            public void onError(int i, String s) {
                KKYUtil.log("发送私聊消息错误enter error" + i + ": " + s);
            }

            @Override
            public void onSuccess(TIMMessage timMessage) {
                KKYUtil.log("发送私聊消息成功!");
            }
        });
    }

    /**
     * 发送点对点自定义消息
     * @param customMsg 自定义消息json格工串
     * @param receiver 接收者id
     */
    public void sendC2CMsg(String customMsg,String receiver){
        TIMMessage msg = new TIMMessage();
        TIMCustomElem elem = new TIMCustomElem();
        elem.setData(customMsg.getBytes());
        elem.setDesc("");
        msg.addElement(elem);
        mC2CConversation = TIMManager.getInstance().getConversation(TIMConversationType.C2C, receiver);
        mC2CConversation.sendMessage(msg, new TIMValueCallBack<TIMMessage>() {
            @Override
            public void onError(int i, String s) {
                KKYUtil.log(TAG, "发送私聊消息错误enter error" + i + ": " + s);
            }

            @Override
            public void onSuccess(TIMMessage timMessage) {
                KKYUtil.log(TAG, "发送私聊消息成功!");
            }
        });
    }

    /**
     * https://www.qcloud.com/doc/product/269/1561
     * ，默认情况下所有消息监听器都将按添加顺序被回调一次 除非用户在OnNewMessages回调中返回true，此时将不再继续回调下一个消息监听器。
     * 群消息回调
     */
    private TIMMessageListener msgListener = new TIMMessageListener() {
        @Override
        public boolean onNewMessages(List<TIMMessage> list) {
            //SxbLog.d(TAG, "onNewMessages readMessage " + list.size());
            //解析TIM推送消息
            parseIMMessage(list);
            return false;
        }
    };

    private void notifyQuitReady() {
        TIMManager.getInstance().removeMessageListener(msgListener);
        if (mRoomView != null) {
            mRoomView.readyToQuit();
        }

    }

    /**
     * initiative主动离开
     * 退出房间
     * @param initiative true 主动退出 false被动退出，如网络或程序异常导致的退出
     */
    public void prepareQuitRoom(boolean initiative) {
        if (initiative) {
            sendGroupMessage(Constants.AVIMCMD_ExitLive, "", new TIMValueCallBack<TIMMessage>() {
                @Override
                public void onError(int i, String s) {

                }
                @Override
                public void onSuccess(TIMMessage timMessage) {
                }
            });
        }
        notifyQuitReady();
    }

    /**
     * 解析消息回调
     *
     * @param list 消息列表
     */
    private void parseIMMessage(List<TIMMessage> list) {
        List<TIMMessage> tlist = list;
        if (tlist.size() > 0) {
            TIMMessage currMsg = tlist.get(0);
            if(currMsg.getConversation().getType()== TIMConversationType.Group) {
                if (mGroupConversation != null) {
                    mGroupConversation.setReadMessage(tlist.get(0));//此处会将私信消息也置为已读，因为群id和私人会话id相同
                }
            }
        }else{
            return;
        }
        if(mRoomView ==null){
            return;
        }

        for (int i = tlist.size() - 1; i >= 0; i--) {
            TIMMessage currMsg = tlist.get(i);
            if(currMsg==null){
                continue;
            }
            mRoomView.onReceiveMsg(currMsg);
            for (int j = 0; j < currMsg.getElementCount(); j++) {
                if (currMsg.getElement(j) == null) {
                    continue;
                }
                TIMElem elem = currMsg.getElement(j);
                TIMElemType type = elem.getType();
                String sendId = currMsg.getSender();
                //系统消息
                if (type == TIMElemType.GroupSystem) {
                    if (TIMGroupSystemElemType.TIM_GROUP_SYSTEM_DELETE_GROUP_TYPE == ((TIMGroupSystemElem) elem).getSubtype()) {
                        mContext.sendBroadcast(new Intent(
                                Constants.ACTION_HOST_LEAVE));
                    }
                }
                //定制消息
                if (type == TIMElemType.Custom) {
                    String id, nickname;
                    if (currMsg.getSenderProfile() != null) {
                        id = currMsg.getSenderProfile().getIdentifier();
                        nickname = currMsg.getSenderProfile().getNickName();
                    } else {
                        id = sendId;
                        nickname = sendId;
                    }
                    String faceUrl=null;
                    if(currMsg.getSenderProfile()!=null){
                        faceUrl=currMsg.getSenderProfile().getFaceUrl();
                    }
                    handleCustomMsg(currMsg,elem, id, nickname,faceUrl);
                    continue;
                }
                //其他群消息过滤
                if (currMsg.getConversation() != null && currMsg.getConversation().getPeer() != null) {
                    if (!CurLiveInfo.getChatRoomId().equals(currMsg.getConversation().getPeer())) {
                        continue;
                    }
                }
                //最后处理文本消息
                if (type == TIMElemType.Text) {
                    if (currMsg.isSelf()) {
                        handleTextMessage(elem, MySelfInfo.getInstance().getNickName());
                    } else {
                        String nickname;
                        if (currMsg.getSenderProfile() != null && (!currMsg.getSenderProfile().getNickName().equals(""))) {
                            nickname = currMsg.getSenderProfile().getNickName();
                        } else {
                            nickname = sendId;
                        }
                        handleTextMessage(elem, nickname);
                    }
                }
            }
        }
    }

    /**
     * 处理文本消息解析
     *
     * @param elem
     * @param name
     */
    public void handleTextMessage(TIMElem elem, String name) {
        TIMTextElem textElem = (TIMTextElem) elem;
        if(mRoomView !=null) {
            mRoomView.refreshText(textElem.getText(), name);
        }
    }


    /**
     * 处理定制消息 赞 关注 取消关注
     *
     * @param elem
     */
    private void handleCustomMsg(TIMMessage message,TIMElem elem, String identifier, String nickname,String avatar) {
        try {
            String customText = new String(((TIMCustomElem) elem).getData(), "UTF-8");
            JSONTokener jsonParser = new JSONTokener(customText);
            // 此时还未读取任何json文本，直接读取就是一个JSONObject对象。
            // 如果此时的读取位置在"name" : 了，那么nextValue就是"yuanzhifei89"（String）
            JSONObject json = (JSONObject) jsonParser.nextValue();
            int action = json.getInt(Constants.CMD_KEY);
            switch (action) {
                case Constants.AVIMCMD_MUlTI_HOST_INVITE:
                    mRoomView.showInviteDialog();
                    break;
                case Constants.AVIMCMD_MUlTI_JOIN:
                    mRoomView.cancelInviteView(identifier);
                    break;
                case Constants.AVIMCMD_MUlTI_REFUSE:
                    mRoomView.cancelInviteView(identifier);
                    break;
                case Constants.AVIMCMD_Praise:
                    mRoomView.refreshThumbUp();
                    break;
                case Constants.AVIMCMD_EnterLive:
                    if (mRoomView != null){
                        try {
                            MsgModel model=gson.fromJson(customText,MsgModel.class);
                            EnterMsg enterMsg=gson.fromJson(model.getActionParam(),EnterMsg.class);
                            mRoomView.memberJoin(enterMsg);
                        }catch (JsonParseException e){
                            e.printStackTrace();
                            if(KKYUtil.DEBUG){
                                Toast.makeText(mContext,"Enter msg parse err",Toast.LENGTH_LONG).show();
                            }
                        }catch (NullPointerException e){
                            e.printStackTrace();
                        }
                    }
                    break;
                case Constants.AVIMCMD_ExitLive:
                    if (mRoomView != null)
                        mRoomView.memberQuit(identifier, nickname);
                    break;
                case Constants.AVIMCMD_MULTI_CANCEL_INTERACT://主播关闭摄像头命令，主播关闭(断开)了和你的连麦状态，得把你的角色更改过来，并关闭你的连麦画面
                    if(RoomVideoRoom.DEBUG_INTERACT) {
                        Toast.makeText(mContext, "收到下麦消息!!!", Toast.LENGTH_LONG).show();
                    }
                    if (mRoomView ==null){
                        return;
                    }
                    message.getConversation().setReadMessage(message);
                    message.remove();
                    //如果是自己关闭Camera和Mic
                    String closeId = json.getString(Constants.CMD_PARAM);
                    if (closeId.equals(MySelfInfo.getInstance().getId())) {//是自己
                        if(RoomVideoRoom.DEBUG_INTERACT) {
                            Toast.makeText(mContext, "被迫下麦!", Toast.LENGTH_LONG).show();
                        }
                        //TODO 被动下麦 下麦 下麦
                        changeRole(Constants.NORMAL_MEMBER_ROLE,false);
                        mRoomView.onCancelMemberInteractVideo();//回复可连麦按钮状态
                    }
                    if(MySelfInfo.getInstance().getIdStatus()== Constants.HOST){
                        if(RoomVideoRoom.DEBUG_INTERACT) {
                            Toast.makeText(mContext, "我是主播，当前连麦数减少了1个", Toast.LENGTH_LONG).show();
                        }
                        mRoomView.hostUpdateVideoCount(closeId);
                    }
                    //其他人关闭小窗口
                    QavsdkControl.getInstance().closeMemberView(closeId);
                    if(RoomVideoRoom.DEBUG_INTERACT) {
                        Toast.makeText(mContext, "关闭了小视频：" + closeId, Toast.LENGTH_LONG).show();
                    }
                    mRoomView.hideInviteDialog();
                    mRoomView.refreshUI(closeId);
                    break;
                case Constants.AVIMCMD_MULTI_HOST_CANCELINVITE:
                    mRoomView.hideInviteDialog();
                    message.getConversation().setReadMessage(message);
                    message.remove();
                    break;
                case Constants.AVIMCMD_MULTI_HOST_CONTROLL_CAMERA:
                    message.getConversation().setReadMessage(message);
                    message.remove();
                    toggleCamera();
                    break;
                case Constants.AVIMCMD_MULTI_HOST_CONTROLL_MIC:
                    message.getConversation().setReadMessage(message);
                    message.remove();
                    toggleMic();
                    break;
                case Constants.AV_IM_CMD_MUlTI_MEMBER_REQ_JOIN_VIDEO://主播收到连麦消息，此消息为C2C消息
                    message.getConversation().setReadMessage(message);
                    message.remove();
                    if(MySelfInfo.getInstance().getIdStatus()== Constants.HOST) {
                        try {
                            MsgModel msgModel = gson.fromJson(customText, MsgModel.class);
                            MultiVideoMsg multiVideoMsg = gson.fromJson(msgModel.getActionParam(), MultiVideoMsg.class);
                            mRoomView.onHostShowMultiVideoDialog(multiVideoMsg.getFuser());//主播端显示连麦请求话框，同意或拒绝
                        }catch (Exception e){
                            CrashReport.postCatchedException(e);
                        }
                    }
                    break;
                case Constants.AV_IM_CMD_MUlTI_MEMBER_REQ_JOIN_VIDEO_AGREE://收到连麦请求应答并且同意，此消息为C2C消息
                    message.getConversation().setReadMessage(message);
                    message.remove();
                    mRoomView.onHostResponseMultiVideo(true,null);//玩家上麦流程，刷新连麦ui
                    break;
                case Constants.AV_IM_CMD_MUlTI_MEMBER_REQ_JOIN_VIDEO_REFUSE://收到连麦请求应答并且被拒绝，此消息为C2C消息
                    message.getConversation().setReadMessage(message);
                    message.remove();
                    if(mContext!=null){
                        mRoomView.onHostResponseMultiVideo(false, mContext.getString(R.string.ui_video_interact_refuse));//提示被拒绝，刷新连麦ui
                    }
                    break;
                default:
                    break;
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (JSONException ex) {
            // 异常处理代码
            ex.printStackTrace();
        }
    }

    public boolean isFrontCamera() {
        return mIsFrontCamera;
    }

    /**
     * 转换前后摄像头
     *
     * @return
     */
    public int switchCamera() {
        AVVideoCtrl avVideoCtrl = QavsdkControl.getInstance().getAVContext().getVideoCtrl();
        int result = avVideoCtrl.switchCamera(mIsFrontCamera ? BACK_CAMERA : FRONT_CAMERA, mSwitchCameraCompleteCallback);
        return result;
    }


    /**
     * 装换摄像头回调
     */
    private AVVideoCtrl.SwitchCameraCompleteCallback mSwitchCameraCompleteCallback = new AVVideoCtrl.SwitchCameraCompleteCallback() {
        protected void onComplete(int cameraId, int result) {
            super.onComplete(cameraId, result);
            if (result == AVError.AV_OK) {
                mIsFrontCamera = !mIsFrontCamera;
                KKYUtil.log("当前为前置摄像头：" + mIsFrontCamera);
                EventBus.getDefault().post(new OnBackCamera(mIsFrontCamera));//用于改变闪光灯状态
            }
        }
    };

    public boolean isMicOpen() {
        return isMicOpen;
    }

    /**
     * 开启Mic
     */
    public void openMic() {
        AVAudioCtrl avAudioCtrl = QavsdkControl.getInstance().getAVContext().getAudioCtrl();//开启Mic
        avAudioCtrl.enableMic(true);
        isMicOpen = true;
    }

    /**
     * 关闭Mic
     */
    public void muteMic() {
        AVAudioCtrl avAudioCtrl = QavsdkControl.getInstance().getAVContext().getAudioCtrl();//关闭Mic
        avAudioCtrl.enableMic(false);
        isMicOpen = false;
    }



    public void toggleFlashLight() {
        AVVideoCtrl videoCtrl = QavsdkControl.getInstance().getAVContext().getVideoCtrl();
        if (null == videoCtrl) {
            return;
        }

        final Object cam = videoCtrl.getCamera();
        if ((cam == null) || (!(cam instanceof Camera))) {
            return;
        }
        final Camera.Parameters camParam = ((Camera) cam).getParameters();
        if (null == camParam) {
            return;
        }

        Object camHandler = videoCtrl.getCameraHandler();
        if ((camHandler == null) || (!(camHandler instanceof Handler))) {
            return;
        }

        //对摄像头的操作放在摄像头线程
        if (flashLgihtStatus == false) {
            ((Handler) camHandler).post(new Runnable() {
                public void run() {
                    try {
                        camParam.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                        ((Camera) cam).setParameters(camParam);
                        flashLgihtStatus = true;
                    } catch (RuntimeException e) {
                    }
                }
            });
        } else {
            ((Handler) camHandler).post(new Runnable() {
                public void run() {
                    try {
                        camParam.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                        ((Camera) cam).setParameters(camParam);
                        flashLgihtStatus = false;
                    } catch (RuntimeException e) {
                    }

                }
            });
        }
    }

    /**
     * 切换前后摄像头时改变状态
     */
    public void flashLightStatusOff(){
        flashLgihtStatus=false;
    }


    private TIMAvManager.RoomInfo roomInfo,recordRoomInfo;
    private long streamChannelID;

    /**
     * 开始推流
     */
    public void pushStream(){
        final TIMAvManager.StreamParam mStreamParam = TIMAvManager.getInstance().new StreamParam();
        mStreamParam.setChannelName("faceLive"+ MySelfInfo.getInstance().getId());
        //mStreamParam.setEncode(TIMAvManager.StreamEncode.HLS);
        mStreamParam.setEncode(TIMAvManager.StreamEncode.HLS_AND_RTMP);
        pushAction(mStreamParam);
    }

    /**
     * 推流
     * @param mStreamParam
     */
    public void pushAction(TIMAvManager.StreamParam mStreamParam) {
        int roomid = (int) QavsdkControl.getInstance().getAVContext().getRoom().getRoomId();
        roomInfo = TIMAvManager.getInstance().new RoomInfo();
        if (roomInfo==null){
            mRoomView.pushStreamFailed("roomInfo is null");
            return;
        }
        roomInfo.setRoomId(roomid);
        roomInfo.setRelationId(CurLiveInfo.getRoomNum());
        //推流的接口
        if (TIMAvManager.getInstance() != null) {
            TIMAvManager.getInstance().requestMultiVideoStreamerStart(roomInfo, mStreamParam, new TIMValueCallBack<TIMAvManager.StreamRes>() {
                @Override
                public void onError(int i, String s) {
                    //Toast.makeText(mContext, "start stream error,try again " + i + " : " + s, Toast.LENGTH_SHORT).show();
                    mRoomView.pushStreamFailed(s);
                }

                @Override
                public void onSuccess(TIMAvManager.StreamRes streamRes) {
                    List<TIMAvManager.LiveUrl> liveUrls = streamRes.getUrls();
                    streamChannelID = streamRes.getChnlId();
                    mRoomView.pushStreamSucc(streamRes);
                }
            });
        }
    }

    /**
     * 停止推流
     */
    public void stopPushAction() {
        List<Long> myList = new ArrayList<Long>();
        myList.add(streamChannelID);
        if (roomInfo==null){
            return;
        }
        try {
            TIMAvManager.getInstance().requestMultiVideoStreamerStop(roomInfo, myList, new TIMCallBack() {
                @Override
                public void onError(int i, String s) {
                    //Toast.makeText(mContext, "stop stream error,try again " + i + " : " + s, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onSuccess() {

                }
            });
        }catch (NullPointerException e){
            CrashReport.postCatchedException(e);
        }

    }

    /**
     * 录制直播，用于回放
     */
    public void roomRecord(final String liveId){
        if(MySelfInfo.getInstance().getIdStatus()!= Constants.HOST){
            return;
        }
        recordRoomInfo= TIMAvManager.getInstance().new RoomInfo();
        recordRoomInfo.setRelationId(MySelfInfo.getInstance().getMyRoomNum());
        recordRoomInfo.setRoomId(MySelfInfo.getInstance().getMyRoomNum());
        TIMAvManager.RecordParam param= TIMAvManager.getInstance().new RecordParam();
        param.setClassId(1);
        param.setFilename(MySelfInfo.getInstance().getId()+"_"+liveId);
        param.setSdkType(TIMAvManager.SDKType.Normal);
        param.setSreenShot(true);//是否截图
        param.setTransCode(true);//是否转码
        param.setWaterMark(false);//是否打水印
        TIMAvManager.getInstance().requestMultiVideoRecorderStart(recordRoomInfo, param,  new TIMCallBack(){
            @Override
            public void onError(int code, String desc) {
                KKYUtil.log("开始录制失败：" + desc);
                if(KKYUtil.DEBUG&&mContext!=null){
                    Toast.makeText(mContext,"start recording err!--"+desc,Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onSuccess() {
                KKYUtil.log("开始录制成功：");
                if(KKYUtil.DEBUG&&mContext!=null){
                    Toast.makeText(mContext,"start recording Success@"+liveId,Toast.LENGTH_LONG).show();
                }
                CurLiveInfo.setIsRecording(true);//标记房间为开启录制功能状态
            }

        });
    }

    /**
     * 停止录制
     */
    public void stopRecord(TIMValueCallBack<List<String>> callBack) {
        if(MySelfInfo.getInstance().getIdStatus()== Constants.HOST){
            if(roomInfo!=null){
                TIMAvManager.getInstance().requestMultiVideoRecorderStop(recordRoomInfo,callBack);
            }
        }
    }

    public void onDestory() {
        mRoomView = null;
        mContext = null;
    }

    /**
     * 改变角色
     *
     * @param role 角色名
     * @param isVideoMember
     */
    public void changeRole(String role, final boolean isVideoMember) {
        QavsdkControl.getInstance().getAvRoomMulti().changeAVControlRole(role, new AVCallback() {
                    @Override
                    public void onComplete(int code, String s) {
                        if (code == AVError.AV_OK) {
                            if (isVideoMember == true) {
                                openCameraAndMic();//打开摄像头
                                sendC2CMessage(Constants.AVIMCMD_MUlTI_JOIN, "", CurLiveInfo.getHostID());//发送回应消息
                            } else {
                                closeCameraAndMic();
                            }
                        } else {

                        }
                    }
                }

        );
    }

}
